/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-21，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.http;

import java.util.HashMap;
import java.util.Map;

import com.chinamobile.ln.ictenterprises.cache.CacheManager;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.utils.JsonParse;

import android.util.Log;

public class HttpAsyncTask extends BaseTask implements Runnable
{
    private static final String TAG = "HttpAsyncTask";
    // 缓存类型
    public static final int CACHE_TYPE_SAVE = 2; // 保存map
    public static final int CACHE_TYPE_ACTION = 3; // 不保存map
    private String _httpUri = "";
    public int _cacheType;
    public boolean isNeedUpadteCache = true;
    private String _httpResponseData;
    private int statusCode;
    private int _jsonParseType;
    public boolean isNotifyUI = true;
    private Step step;
    private String tmpcookies;

    /**
     * 构造方法
     * @param step
     * @param cacheType
     */
    public HttpAsyncTask(Step step, int cacheType, String tmpcookies,
        int _jsonParseType)
    {
        this.step = step;
        this._cacheType = cacheType;
        this.tmpcookies = tmpcookies;
        this._jsonParseType = _jsonParseType;
        this._httpUri = step.getUrl();
    }

    @Override
    public void run()
    {
        Log.d(TAG, "开始发送http请求");
        try
        {
            request();
        }
        catch (NullPointerException e)
        {
            exceptionHandle("NullPointerException", e);
        }
        catch (Exception e)
        {
            exceptionHandle("Exception", e);
        }
    }

    /**
     * 发送http请求
     */
    private void request()
    {
        Map<String, Object> _dataMapResult;
        Map<String, Object> retMapResult = HttpSend.send(step, tmpcookies);
        _httpResponseData = (String) retMapResult.get(GlobalSetting.RET_DATA);
        statusCode = (Integer) retMapResult.get(GlobalSetting.STUATUS_CODE);
        tmpcookies = (String) retMapResult.get(GlobalSetting.TMP_COOKIES);
        Log.i(TAG, "响应报文：" + _httpResponseData);
        _dataMapResult = JsonParse.parseJSON(_httpResponseData, _jsonParseType);
        _dataMapResult.put(GlobalSetting.STUATUS_CODE, statusCode);
        _dataMapResult.put(GlobalSetting.TMP_COOKIES, tmpcookies);
        if (_cacheType == CACHE_TYPE_SAVE)
        {
            CacheManager.getInstance().saveCache(_httpUri, _dataMapResult);
        }
        if (isNotifyUI)
        {
            onReturnData(_dataMapResult);
        }
    }

    @Override
    public void notifyUIStatus(int what)
    {
        if (_uiHandler != null)
        {
            if (!_uiHandler.hasMessages(what))
            {
                _uiHandler.sendEmptyMessage(what);
            }
        }
    }

    @Override
    public void notifyUIObject(int what, Object obj)
    {
        if (_uiHandler != null)
        {
            if (!_uiHandler.hasMessages(what, obj))
            {
                _uiHandler.sendMessage(_uiHandler.obtainMessage(what, obj));
            }
        }
    }

    @Override
    public void onReturnData(Object result)
    {
        notifyUIObject(TASK_NOTIFY_RETURN_DATA, result);
    }

    @Override
    public void exceptionHandle(String what, Exception e)
    {
        notifyUIStatus(TASK_NOTIFY_CONNECTION_FAIL);
    }

    public boolean onPreExecuteCheckCache()
    {
        Object obj = CacheManager.getInstance().checkCache(_httpUri);
        if (obj != null)
        {
            @SuppressWarnings("unchecked")
            Map<String, Object> objMap = (HashMap<String, Object>) obj;
            checkCacheUpdateTime(objMap);
            onReturnData(objMap);
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 检查是否需要发送请求（要求:5分钟内不重发请求）
     * 
     * @param objMap
     */
    private void checkCacheUpdateTime(Map<String, Object> objMap)
    {
        String cacheTime = (String) objMap.get(Config.CACHE_TIME);
        long time = Long.valueOf(cacheTime);
        long temp = System.currentTimeMillis() - time;
        if (temp < 0)
        {
            temp = -temp;
        }
        if (temp < Config.updateCacheTimes)
        {
            isNeedUpadteCache = false;
        }
    }
}
